// main.js
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import axios from "axios";
import 'dotenv/config';

const APIKEY = process.env.API_KEY;
const server = new Server(
  { name: 'mcp-node-server', version: '1.0.0' },
  { capabilities: { tools: {} } }
);

  // 1. 告诉客户端：我有哪些工具
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: 'getWeather',
      description: '获取指定城市实时天气',
      inputSchema: {
        type: 'object',
        properties: {
          city: { type: 'string', description: '城市名称，如 北京' }
        },
        required: ['city']
      }
    }
  ]
}));

// 2. 实现工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;
  if (name !== 'getWeather') throw new Error('Unknown tool');

  const { city } = args;
  const apiUrl = "http://apis.juhe.cn/simpleWeather/query";

  // 接口请求入参配置
  const requestParams = {
    key: APIKEY,
    city: city || "北京",
  };

  // 发起接口网络请求
  const { status, data } = await axios.get(apiUrl, {params: requestParams})

  if (status !== 200) throw new Error(`状态返回 ${status}`)

  // 解析响应结果
  return {
    content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
  };
});

// 启动 stdio 通道
const transport = new StdioServerTransport();
server.connect(transport);

console.log("🚀 The Weather MCP server is started via stdio mode.");